package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ModifyPhoneSuccessEvent;
import com.uetoken.cn.bean.UploadFileBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.GlideApp;
import com.uetoken.cn.utils.GlideUtils;
import com.uetoken.cn.utils.PhotoUtils;
import com.uetoken.cn.view.DialogHelper;
import com.yanzhenjie.durban.Durban;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * 用户信息
 */
public class UserInfoActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView           mIvBack;
    @BindView(R.id.tv_title)
    TextView            mTvTitle;
    @BindView(R.id.iv_activity_user_info_head_photo)
    QMUIRadiusImageView mIvActivityUserInfoHeadPhoto;
    @BindView(R.id.iv_activity_user_info_arrow_right)
    ImageView           mIvActivityUserInfoArrowRight;
    @BindView(R.id.rl_activity_user_info_head_photo)
    RelativeLayout      mRlUserInfoHeadPhoto;
    @BindView(R.id.tv_activity_user_info_nickname)
    TextView            mTvActivityUserInfoNickname;
    @BindView(R.id.rl_activity_user_info_nickname)
    RelativeLayout      mRlUserInfoNickname;
    @BindView(R.id.tv_activity_user_info_name)
    TextView            mTvActivityUserInfoName;
    @BindView(R.id.iv_activity_user_info_head_certification_status)
    ImageView           mIvActivityUserInfoHeadCertificationStatus;
    @BindView(R.id.rl_activity_user_info_name)
    RelativeLayout      mRlUserInfoName;
    @BindView(R.id.tv_activity_user_info_phone_number)
    TextView            mTvActivityUserInfoPhoneNumber;
    @BindView(R.id.rl_activity_user_info_phone_number)
    RelativeLayout      mUserInfoPhoneNumber;
    private PhotoUtils mPhotoUtils;
    /**
     * 裁剪图片Intent请求码
     */
    private static final int CROP_IMAGE_REQUEST_CODE     = 200;
    /**
     * 修改昵称Intent请求码
     */
    private static final int MODIFY_NICKNAME_REQUEST_CODE = 300;
    /**
     * 上传头像的请求码
     */
    public static final  int NETWORK_REQUEST_UPLOAD_FILE = 10;
    /**
     * 修改头像的请求码
     */
    private static final int NETWORK_REQUEST_MODIFY_HEAD = 20;
    /**
     * 服务器返回的头像地址
     */
    private String headPath;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this,android.R.color.white),true);
        BarUtils.setStatusBarLightMode(this,true);

        mIvBack.setVisibility(View.VISIBLE);
        mTvTitle.setText(getString(R.string.str_use_info));

        EventBus.getDefault().register(this);

        mTvActivityUserInfoNickname.setText(SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_NAME,""));
        mTvActivityUserInfoPhoneNumber.setText(SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MOBILE_NO,""));
        GlideApp.with(this).load(SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_HEAD_PHOTO,"")).apply(GlideUtils.getOptions()).into(mIvActivityUserInfoHeadPhoto);
    }

    @Override
    public void initData() {
        mPhotoUtils = new PhotoUtils();

        mPhotoUtils.setPhotoPathListener(new PhotoUtils.PhotoPathListener() {
            @Override
            public void getPathSuccess(String path) {
                mPhotoUtils.cropImage(UserInfoActivity.this, path, 1, 1);
            }
        });
    }

    @Override
    public void init() {

    }

    @OnClick({R.id.iv_back, R.id.rl_activity_user_info_head_photo, R.id.rl_activity_user_info_nickname, R.id.rl_activity_user_info_name, R.id
            .rl_activity_user_info_phone_number})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_activity_user_info_head_photo:
                selectMode();
                break;
            case R.id.rl_activity_user_info_nickname:
                Intent modifyNickNameIntent = new Intent(this, ModifyUserInfoActivity.class);
                modifyNickNameIntent.putExtra(ModifyUserInfoActivity.MODIFY_USER_INFO, 1);
                modifyNickNameIntent.putExtra("nickname",mTvActivityUserInfoNickname.getText().toString());
                startActivityForResult(modifyNickNameIntent,MODIFY_NICKNAME_REQUEST_CODE);
                break;
            case R.id.rl_activity_user_info_name:
                break;
            case R.id.rl_activity_user_info_phone_number:
                Intent modifyPhoneIntent = new Intent(this, ModifyUserInfoActivity.class);
                modifyPhoneIntent.putExtra(ModifyUserInfoActivity.MODIFY_USER_INFO, 2);
                startActivity(modifyPhoneIntent);
                break;

        }
    }

    /**
     * 拍照或者从相册选择
     */
    private void selectMode() {
        //当前手机版本低于23时，用此方法来判断相机是否可用(主要是用户手动关闭权限)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            if (!PhotoUtils.cameraIsCanUse()){
                //相机不可用
                ToastUtils.showShort(getResources().getString(R.string.str_camera_not_use));
                return;
            }
        }

        AndPermission.with(this).runtime().permission(Permission.Group.CAMERA,Permission.Group.STORAGE).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                DialogHelper.showCameraDialog(mPhotoUtils);
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                ToastUtils.showShort(getResources().getString(R.string.str_camera_not_use));
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CROP_IMAGE_REQUEST_CODE:
                if (resultCode==RESULT_OK){
                    ArrayList<String> mImageList = Durban.parseResult(data);
                    if (!mImageList.isEmpty()) {
                        //裁剪图片成功后开始调用接口修改头像
                        modifyHeadview(mImageList.get(0));

                    }
                }
                break;
            case MODIFY_NICKNAME_REQUEST_CODE:
                if (resultCode==RESULT_OK){
                    mTvActivityUserInfoNickname.setText(data.getStringExtra("nickname"));
                }
                break;
        }
    }

    /**
     * 修改头像
     *
     * @param path 图片路径
     */
    private void modifyHeadview(String path) {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getUploadFileUrl(), NETWORK_REQUEST_UPLOAD_FILE,
                Params.getUploadFileUrlParams(PhotoUtils.imageToBase64(path), ImageUtils.getImageType(path).getValue()));
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        dissmissDialog();
        switch (requestCode) {
            case NETWORK_REQUEST_UPLOAD_FILE:
                UploadFileBean uploadFileBean = new Gson().fromJson(response, UploadFileBean.class);
                if (uploadFileBean.getResult()>0){
                    String url = uploadFileBean.getData().getFullurl();
                    headPath = url;
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_HEAD_PHOTO,url);
                    //调用修改头像接口
                    OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getModifyUserInfoUrl(), NETWORK_REQUEST_MODIFY_HEAD,
                                        Params.getModifyUserInfoParams("3", url, ""));
                }else{
                    ToastUtils.showShort(uploadFileBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_MODIFY_HEAD:
                JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
                String message = obj.get("message").getAsString();
                if (obj.get("result").getAsInt() > 0) {
                    GlideApp.with(UserInfoActivity.this).load(headPath).into(mIvActivityUserInfoHeadPhoto);
                    //发送广播更新下主界面的头像
                    Intent successIntent = new Intent();
                    successIntent.setAction("paySuccess");
                    sendBroadcast(successIntent);
                } else {
                    ToastUtils.showShort(message);
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPhone(ModifyPhoneSuccessEvent event) {
        mTvActivityUserInfoPhoneNumber.setText(event.getPhone());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
